<?php
/**
 * @description:
 * @author     : Geomen
 * @time       : 2018/4/24 14:22
 */


namespace App\Component;


use Symfony\Component\Console\Helper\HelperInterface;
use Symfony\Component\Console\Helper\HelperSet;

class CustomHelper implements HelperInterface
{

    /**
     * Sets the helper set associated with this helper.
     */
    public function setHelperSet(HelperSet $helperSet = null)
    {
        // TODO: Implement setHelperSet() method.
    }

    /**
     * Gets the helper set associated with this helper.
     *
     * @return HelperSet A HelperSet instance
     */
    public function getHelperSet()
    {
        // TODO: Implement getHelperSet() method.
    }

    /**
     * Returns the canonical name of this helper.
     *
     * @return string The canonical name
     */
    public function getName()
    {
        // TODO: Implement getName() method.
    }

    /**
     * 文件大小格式化
     * @param $size
     *
     * @return string
     */
    public static function formatFileSize($size)
    {
        $units = array( 'B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
        $power = $size > 0 ? floor(log($size, 1024)) : 0;
        return number_format($size / pow(1024, $power), 2, '.', ',') . ' ' . $units[$power];
    }

    /**
     * 数据库备份
     */
    public static function backupsDb()
    {
        $sql_filename='ls5h_'.date('YmdHis').'.'.'sql';
        $to_file_name = storage_path('app/backups/'.$sql_filename);
        $tables = \DB::select('SHOW TABLES');
        $object =  json_decode( json_encode( $tables),true);

        $names = array();
        foreach($object as $k => $v){
            $names[] = $v['Tables_in_ls5h'];
        }

        $info = "-- ----------------------------\r\n";
        $info .= "-- 日期：".date("Y-m-d H:i:s",time())."\r\n";
        $info .= "-- 陈志明\r\n";
        $info .= "-- 备份\r\n";
        $info .= "-- ----------------------------\r\n\r\n";
        file_put_contents($to_file_name,$info,FILE_APPEND);

        //将每个表的表结构导出到文件
        foreach($names as $val) {

            $sql = "show create table " . $val;
            //$res = mysql_query($sql,$link);
            $ress = \DB::select($sql);
            $res = json_decode(json_encode($ress), true);
            //print_r($res);die;
            // $row = mysql_fetch_array($res);
            $info = "-- ----------------------------\r\n";
            $info .= "-- Table structure for `" . $val . "`\r\n";
            $info .= "-- ----------------------------\r\n";
            $info .= "SET FOREIGN_KEY_CHECKS = 0;\r\n";
            $info .= "DROP TABLE IF EXISTS `" . $val . "`;\r\n";
            $info .= "SET FOREIGN_KEY_CHECKS = 1;\r\n";
            $sqlStr = $info . $res[0]['Create Table'] . ";\r\n\r\n";
            //追加到文件
            file_put_contents($to_file_name, $sqlStr, FILE_APPEND);

        }

        //将每个表的数据导出到文件
        foreach($names as $val){
            $sql = "select * from ".$val;
            $ress = \DB::select($sql);
            $res = json_decode( json_encode( $ress),true);
            //如果表中没有数据，则继续下一张表
            if(count($res)<1) continue;
            //
            $info = "-- ----------------------------\r\n";
            $info .= "-- Records for `".$val."`\r\n";
            $info .= "-- ----------------------------\r\n";
            file_put_contents($to_file_name,$info,FILE_APPEND);
            //读取数据


            foreach($res as $z){
                $sqlStr = "INSERT INTO `".$val."` VALUES (";
                foreach($z as $zd){
                    $sqlStr .= "'".$zd."', ";
                }
                //去掉最后一个逗号和空格
                $sqlStr = substr($sqlStr,0,strlen($sqlStr)-2);
                $sqlStr .= ");\r\n";
                file_put_contents($to_file_name,$sqlStr,FILE_APPEND);
            }


            file_put_contents($to_file_name,"\r\n",FILE_APPEND);

        }
    }

    /**
     * 还原备份
     *
     * @param string $filename
     *
     * @return array|string
     */
    public static function restoreDb($filename = ''){
        header('content-type:text/html;charset=utf-8');
        $mysql_file=storage_path('app/backups/'.$filename); //指定要恢复的MySQL备份文件路径,请自已修改此路径

        if (file_exists($mysql_file)) {
            $sql_value="";
            $cg=0;
            $sb=0;
            $sqls=file($mysql_file);
            foreach($sqls as $sql)
            {
                $sql_value.=$sql;

            }
            // print_r($sql_value);die;
            $a=explode(";\r\n", $sql_value); //根据";\r\n"条件对数据库中分条执行
            $total=count($a)-1;
            $sb_command = array();
            \DB::select("set names 'utf8'");
            for ($i=0;$i<$total;$i++)
            {
                \DB::select("set names 'utf8'");
                //执行命令
                if(\DB::select($a[$i])) //成功
                {
                    $cg+=1;
                }else{ //失败
                    $sb+=1;
                    $sb_command[$sb]=$a[$i];
                }
            }
            return ['success' => $cg,'fail' => $sb, 'fail_command' => $sb_command];
        }else{
            return "MySQL备份文件不存在，请检查文件路径是否正确！";
        }




    }
}